﻿using System;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Area;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 用户(操作员)中心接口
    /// </summary>
    [Authorize]
    public class UserCenterController : BaseApiController //BaseCrudApiController<Staff>
    {
        private static ILogger<UserCenterController> _logger;
        private readonly TokenHelper _tokenHelper;
        private readonly IUserCenterLogic _userCenterLogic;
        private readonly ISignService _signService;

        /// <inheritdoc />
        public UserCenterController(
            ISignService signService,
            ILogger<UserCenterController> logger,
            IBaseInfoLogic baseInfoLogic,
            IUserCenterLogic userCenterLogic,
            TokenHelper tokenHelper)
        {
            _logger = logger;
            _userCenterLogic = userCenterLogic;
            _tokenHelper = tokenHelper;
            _signService = signService;
        }

        /// <summary>
        /// 通过Token获取用户信息
        /// </summary>
        [HttpGet]
        public IActionResult UserInfo()
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                var dataResult = new DataResult
                {
                    errcode = 0,
                    msg = "ok",
                    data = _userCenterLogic.UserInfo(token.payload.id)
                };
                return Ok(dataResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                var baseResult = new BaseResult
                {
                    errcode = 1,
                    msg = e.Message
                };
                return Ok(baseResult);
            }
        }

        /// <summary>
        /// 登出
        /// </summary>
        [HttpGet]
        public IActionResult LogOut()
        {
            //验证token

            //var token = _tokenHelper.GetTokenByHttpContext();
            _signService.ClearToken();
            return Ok(new BaseResult
            {
                errcode = 0,
                msg = "ok"
            });
        }

        /// <summary>
        /// 查询所有用户数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/System/UserSite")]
        public IActionResult SelectUser()
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                var data = _userCenterLogic.SelectUserSite(token.payload.id);
                var result = new AreaOperatorResult
                {
                    data = data
                };
                return Ok(result);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取用户数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 根据项目Id查询用户数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/System/UserSite/{projectId}")]
        public IActionResult SelectUser(string projectId)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                var data = _userCenterLogic.SelectUserSite(token.payload.id, projectId);
                var result = new AreaOperatorResult
                {
                    data = data
                };
                return Ok(result);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取用户数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 初始化密码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Users/IniPassword")]
        public IActionResult PasswordIniPut([FromBody] dynamic obj)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //添加验证
                string id, password;
                try
                {
                    id = obj.id.ToString();
                    password = obj.password.ToString();
                }
                catch (RuntimeBinderException re)
                {
                    _logger.LogError(re.Message, re);
                    return Ok(new BaseResult {errcode = 1, msg = "参数错误"});
                }
                //判断密码是否正确
                var verify = _userCenterLogic.VerifyPassWord(token.payload.id, password);
                if (!verify)
                    return Ok(new BaseResult {errcode = 1, msg = "操作员密码错误"});
                var result = _userCenterLogic.InitialisePassWord(id, out var refPassword, out var message);
                return Ok(!result
                    ? new BaseResult {errcode = 1, msg = message}
                    : new PassWordResult {errcode = 0, msg = "ok", id = id, password = refPassword});
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult {errcode = 1, msg = "初始化密码失败"});
            }
        }

        /// <summary>
        /// 查询操作员密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/System/Users/Password/{id}/{password}")]
        public IActionResult GetPassword(string id, string password)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();

                //判断密码是否正确
                var verify = _userCenterLogic.VerifyPassWord(token.payload.id, password);
                if (!verify)
                    return Ok(new BaseResult {errcode = 1, msg = "操作员密码错误"});
                var result = _userCenterLogic.GetPassWord(id, out var message);
                return Ok(new PassWordResult {errcode = 0, msg = "ok", id = id, password = result});
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new BaseResult {errcode = 1, msg = "初始化密码失败"});
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Users/Password")]
        public IActionResult PasswordPut([FromBody] dynamic obj)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                var id = token.payload.id;
                var result = _userCenterLogic.EditPassWord(id, obj, out string message);
                if (!result)
                {
                    return Ok(
                        new
                        {
                            errcode = 1,
                            msg = $"{message}"
                        });
                }
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok"
                    });
            }
            catch (Exception e)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"修改密码数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Users")]
        public IActionResult AddUser([FromBody] dynamic obj)
        {
            try
            {
                var result = _userCenterLogic.AddUser(obj, out string exception);
                if (!result)
                {
                    return Ok(
                        new
                        {
                            errcode = 1,
                            msg = $"{exception}"
                        });
                }
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"添加用户数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Users/Update")]
        public IActionResult UpdateUser([FromBody] dynamic obj)
        {
            try
            {
                var result = _userCenterLogic.EditUser(obj, out string exception);
                if (!result)
                {
                    return Ok(
                        new
                        {
                            errcode = 1,
                            msg = $"{exception}"
                        });
                }
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"修改用户数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Users/Delete")]
        public IActionResult DeleteUser([FromBody] dynamic obj)
        {
            try
            {
                var id = obj.id.ToString();
                var result = _userCenterLogic.DeleteUser(id, out string exception);
                if (!result)
                {
                    return Ok(
                        new
                        {
                            errcode = 1,
                            msg = $"{exception}"
                        });
                }
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"删除用户数据错误,错误:{e.Message}"
                });
            }
        }

       
    }
}